package models.user;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

import play.Logger;
import play.db.ebean.Model;
import utils.MengException;

/**
 * 用户教育经历
 * @author zhangpeng
 *
 */

@Entity
@Table(name="edu_user_info")
public class EduUserInfo extends Model{

	private static final long serialVersionUID = 1L;
	
	@Id
	public long id;
	
	public String username;
	/**
	 * 毕业学校
	 */
	public String graduate;
	/**
	 * 学历
	 */
	public String education;
	
	public static EduUserInfo getInstances(){
		return new EduUserInfo();
	}
	
	public static Model.Finder<Long, EduUserInfo> find = new Model.Finder<Long, EduUserInfo>(Long.class, EduUserInfo.class);
	
	/**
	 * 创建用户教育经历
	 * 
	 * @param eui
	 * @return
	 * @throws MengException
	 */
	public boolean createEUI(EduUserInfo eui) throws MengException {

		if (UserInfo.getInstances().verifyUsername(eui.username)) {
			throw new MengException("400001", "用户名不存在");
		}

		if (verifyEduUserInfo(eui.username)) {
			throw new MengException("400002", "用户教育经历已存在");
		}

		try {
			eui.save();
			return true;
		} catch (Throwable t) {
			t.printStackTrace();
			Logger.error("UserInfo createEUI Exception," + t.getMessage());
			throw new MengException("400003", "用户教育经历保存失败");
		}
	}

	public boolean createEUI(UserInfo ui) throws MengException {

		if (verifyEduUserInfo(ui.username)) {
			throw new MengException("400008", "用户基本信息已存在");
		}
		EduUserInfo eui = getInstances();
		eui.username = ui.username;
		try {
			eui.save();
			return true;
		} catch (Throwable t) {
			t.printStackTrace();
			Logger.error("UserInfo createBUI Exception," + t.getMessage());
			throw new MengException("400009", "用户基本信息保存失败");
		}
	}

	/**
	 * 用户教育经历修改
	 * 
	 * @param eui
	 * @return
	 * @throws MengException
	 */
	public boolean modifyEUI(EduUserInfo eui) throws MengException {

		if (UserInfo.getInstances().verifyUsername(eui.username)) {
			throw new MengException("400004", "用户名不存在");
		}
		eui.id = getEUI(eui.username).id;

		try {
			eui.update();
			return true;
		} catch (Throwable t) {
			t.printStackTrace();
			Logger.error("UserInfo modifyEUI Exception," + t.getMessage());
			throw new MengException("400005", "用户教育经历修改失败");
		}
	}

	/**
	 * 获取用户教育经历
	 * 
	 * @param username
	 * @return
	 * @throws MengException
	 */
	public EduUserInfo getEUI(String username) throws MengException {

		if (UserInfo.getInstances().verifyUsername(username)) {
			throw new MengException("400006", "用户名不存在");
		}

		try {

			return find.where().eq("username", username).findUnique();
		} catch (Throwable t) {
			t.printStackTrace();
			Logger.error("UserInfo getEUI Exception," + t.getMessage());
			throw new MengException("400007", "获取用户教育经历失败");
		}
	}
	
	public boolean verifyEduUserInfo(String username) throws MengException {

		if (getEUI(username) != null) {
			return true;
		}

		return false;
	}


}
